#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "1my_socket.hpp"
#include "1my_protocol.hpp"

static void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port ip\n" << std::endl;
}

int main(int argc, char* argv[]) //./client port ip
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    std::string ip = argv[2];

    SocketServer sockfd;
    sockfd.Socket();
    bool c = sockfd.Connect(port, ip);
    if(c == false)
    {
        exit(1);
    }

    srand(time(nullptr));
    int cnt = 1;
    const std::string ops = "+-*/%!@#";
    std::string package_stream;
    while(cnt <= 10)
    {
        std::cout << "test--------------" << cnt << std::endl;
        Request req;
        req._x = rand() % 100 + 1;
        usleep(1000);
        req._y = rand() % 100;
        usleep(1000);
        req._op = ops[rand() % ops.size()];
        req.PrintVariable();

        std::string content;
        req.Serialize(&content);
        std::string package = Encode(content);
        write(sockfd.Fd(), package.c_str(), package.size());

        char buffer[1024];
        ssize_t r = read(sockfd.Fd(), buffer, sizeof(buffer));
        if (r > 0)
        {
            buffer[r] = 0;
            package_stream += buffer;
            std::cout << package_stream << std::endl;
            std::string read_content;
            bool d = Decode(package_stream, &read_content);
            assert(d);
            Response res;
            res.Deserialize(read_content);
            res.PrintVariable();
        }
        std::cout << "---------------" << std::endl;
        cnt++;
        sleep(1);
    }
    
    sockfd.Close();

    return 0;
}